package com.qf.dao.impl;

import com.qf.dao.GoodsDao;
import com.qf.entity.Goods;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package com.qf.dao.impl
 * @description: ${TODO}
 * @date 2022/6/23 11:41
 */
public class GoodsDaoImpl implements GoodsDao {
    @Override
    public long selectCount(String where, List<Object> params) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return qr.query("select count(*) from tb_goods "+where, new ScalarHandler<>(),params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Goods> selectByPage(int pn, int ps, String where, List<Object> params) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        params.add((pn-1)*ps);
        params.add(ps);
        try {
            return qr.query("select * from tb_goods "+where +" order by id limit ?,?", new BeanListHandler<>(Goods.class),params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Goods selectById(int id) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return qr.query("select * from tb_goods where id=?", new BeanHandler<>(Goods.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Goods goods) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        Object[] params={goods.getName(),goods.getPubdate(),goods.getPicture(),goods.getPrice(),goods.getStar(),goods.getIntro(),goods.getTypeid()};
        try {
            qr.update("insert into tb_goods values(null,?,?,?,?,?,?,?);",params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
